
import uuid
import openpyxl
import pytest
from fastapi import HTTPException
from model.entitys import CaseGroup, Execut, Case, Status

# class ExcelCase():
#     id: str
#     title: str
#     enable: str
#     before_handle: str
#     user_var: str
#     method: str
#     database_info: str
#     driver_info: str
#     header: str
#     url_or_sql: str
#     element_info: str
#     param_type: str
#     params: str
#     file_info: str
#     var_name: str
#     need_data: str
#     random_info: str
#     forced_type: str
#     after_handle: str
#     expected_results: str
#     actual_result_template: str
#     actual_results: str
#     whether: str
#     current_info: str

class ExcelHandle:

    def __init__(self, filepath):
        self.wb = openpyxl.load_workbook("./"+filepath)
        self.titels = [
            'id', 'title', 'enable', 'user_var', 'before_handle', 'method', 'database_info', 'driver_info', 'header',
            'url_or_sql', 'element_info',
            'param_type', 'params', 'file_info', 'extract_var',
            'var_name', 'need_data', 'random_info',
            'forced_type', 'after_handle', 'assert_info', 'expected_results', 'actual_result_template',
            'actual_results', 'whether'
        ]

    def get_data(self, mode: str = "r", db=None):
        dataList = []
        case_group_list = []

        for sheet in self.wb.sheetnames:
            if mode == "w":
                if db.query(CaseGroup).filter(CaseGroup.title == sheet).first():
                    continue

                cg = {
                    "id": uuid.uuid1().__str__(),
                    "title": sheet,
                    "rerun_times": 3,
                    "executing": Execut.DEATH,
                    "case_number": self.wb[sheet].max_row - 1,
                    "pass_number": 0,
                    "fail_number": 0,
                    "remarks": "导入用例"
                }
                case_group_list.append(cg)

            for i in range(2, self.wb[sheet].max_row + 1):
                dataMap = {}
                # ec = ExcelCase()

                # if self.wb[sheet].cell(row=i, column=3).value is False and mode == "r":
                #     continue

                for j in range(1, self.wb[sheet].max_column + 1):
                    dataMap[self.titels[j - 1]] = self.wb[sheet].cell(row=i, column=j).value
                    # setattr(ec, self.titels[j - 1], self.wb[sheet].cell(row=i, column=j).value)

                    if mode == "r":
                        dataMap["current_info"] = {
                            "sheet": sheet,
                            "row": i
                        }
                        # ec.current_info = {
                        #     "sheet": sheet,
                        #     "row": i
                        # }

                if mode == "w":
                    dataMap["id"] = uuid.uuid1().__str__()
                    dataMap["case_group_id"] = cg["id"]

                if mode == "r" and (dataMap["enable"] is False or dataMap["enable"] == "Status.DISABLE"):
                    dataList.append(pytest.param(dataMap, marks=pytest.mark.skip("skip")))
                else:
                    dataList.append(dataMap)
                    # dataList.append(ec)

        if mode == "w":
            try:
                db.bulk_insert_mappings(CaseGroup, case_group_list)
                db.bulk_insert_mappings(Case, dataList)

            except Exception as e:
                db.rollback()

                raise HTTPException(status_code=400, detail=repr(e))

            else:
                db.commit()

            finally:
                db.close()

        return dataList





















